<?php

namespace App\Livewire;

use App\Models\Actor;
use App\Models\Video;
use Illuminate\Support\Collection;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class ActorList extends Component
{
    use WithPagination;

    #[Url]
    public string $sortBy = 'updated_at';

    #[Url]
    public string $abbr = '';

    public int $page = 1;

    public Collection $collection;

    public bool $hasMorePages;

    public function mount(): void
    {
        $this->collection = Collection::make();

        $this->loadMore();
    }

    public function loadMore(): void
    {
        $collection = Actor::addSelect([
            'hot_count' => Video::selectRaw('sum(`visits`)')
                ->join('actor_video', 'video_id', '=', 'videos.id')
                ->whereColumn('actor_id', '=', 'actors.id'),
        ])
            ->when($this->abbr, fn ($query, $value) => $query->where('abbr', 'like', $this->abbr.'%'))
            ->latest($this->sortBy)
            ->latest('id')
            ->simplePaginate(perPage: 16, page: $this->page);

        $this->collection->push(...$collection->items());

        if ($this->hasMorePages = $collection->hasMorePages()) {
            $this->page++;
        }
    }

    public function render()
    {
        return view('livewire.actor-list');
    }
}
